package cn.itcast.travel.dao.impl;

import cn.itcast.travel.dao.RoutDao;
import cn.itcast.travel.domain.Route;
import cn.itcast.travel.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class RoutDaoImp implements RoutDao {
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public int findTotalCount(int id ,String rname) {
        String sql="select count(*) from tab_route where 1=1";
        StringBuilder stringBuilder=new StringBuilder(sql);
        List params=new ArrayList();
        if (id!=0){
           stringBuilder.append(" and cid=? ");
           params.add(id);
        }
        if (rname!=null||rname.length()>0){
            stringBuilder.append(" and rname like ?");
            params.add("%"+rname+"%");
        }
        sql=stringBuilder.toString();
            return jdbcTemplate.queryForObject(sql,Integer.class,params.toArray());
    }

    @Override
    public List<Route> findByPage(int cid, int start, int pageSize, String rname) {
       // String sql="select * from tab_route where cid=? limit ? , ?";
        String sql="select * from tab_route where 1=1";
        StringBuilder stringBuilder=new StringBuilder(sql);
        List params=new ArrayList();
        if (cid!=0){
            stringBuilder.append(" and cid=? ");
            params.add(cid);
        }
        if (rname!=null||rname.length()>0){
            stringBuilder.append(" and rname like ?");
            params.add("%"+rname+"%");
        }
        stringBuilder.append(" limit ? , ?");
        params.add(start);
        params.add(pageSize);
        sql=stringBuilder.toString();
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<Route>(Route.class),params.toArray());
    }

    @Override
    public Route findOne(int rid) {
        String sql="select * from tab_route where rid=?";
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Route>(Route.class),rid);
    }

    @Override
    public List<Route> findIndex() {
        String sql="SELECT * from tab_route LIMIT 0,24 ";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<Route>(Route.class));
    }

    @Override
    public List<Route> findAll() {
        String sql = "select * from tab_route";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<Route>(Route.class));
    }
}
